﻿using System;


namespace FeedbackNetwork.network.layer
{
    class Softmax : Layer
    {
       
        public Softmax() : base(1, 1)
        {

        }
        public override FloatTensor[] Backward(FloatTensor[] input)
        {
            return input;
            /*
            float[] data = input.GetData();
            for(int i = 0; i < data.Length; i++)
            {
                data[i] = data[i] * (1 - data[i]); 
            }
            return new FloatTensor(data, input.GetShape());
            */
        }

        public override FloatTensor Forward(FloatTensor input)
        {
            FloatTensor result = new FloatTensor(input.GetShape(), 0f);
            int batch = input.GetDimensionShape(0);
            for(int i = 0; i < batch; i++)
            {
                FloatTensor temp = input.GetDimensionData(0, i);
                temp = Calculate(temp);
                result.SetDimensionData(0, i, temp);
            }
            return result;
        }

        private FloatTensor Calculate(FloatTensor input)
        {
            /**/
            float[] data = input.GetData();
            float sum = 0f;
            for (int i = 0; i < data.Length; i++)
            {
                float temp = (float)Math.Pow(Math.E, data[i]);
                sum += temp;
                data[i] = temp;
            }
            if (sum != 0)
            {
                for (int i = 0; i < data.Length; i++)
                    data[i] = data[i] / sum;
            }
            return new FloatTensor(data, input.GetShape());
            
        }

        public override string ToString()
        {
            return new string("Softmax 层");
        }
    }
}
